package top.wilsonlv.jaguar.cloud.upms.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.wilsonlv.jaguar.cloud.upms.entity.UserFace;
import top.wilsonlv.jaguar.cloud.upms.mapper.UserFaceMapper;
import top.wilsonlv.jaguar.rediscache.AbstractRedisCacheService;

/**
 * @author lvws
 * @since 2022/3/25 0025
 */
@Service
@RequiredArgsConstructor
public class UserFaceService extends AbstractRedisCacheService<UserFace, UserFaceMapper> {

    private final FaceService faceService;

    public UserFace getByUserId(Long userId) {
        return this.unique(Wrappers.lambdaQuery(UserFace.class)
                .eq(UserFace::getUserId, userId));
    }

    @Transactional
    public void bindFace(Long userId, String userFaceImage) {
        UserFace userFace = this.getByUserId(userId);
        if (userFace == null) {
            if (StringUtils.hasText(userFaceImage)) {
                String feature = faceService.face2Feature(userFaceImage);
                userFace = new UserFace();
                userFace.setUserId(userId);
                userFace.setUserFaceImage(userFaceImage);
                userFace.setUserFaceFeature(feature);
                this.insert(userFace);
            }
        } else {
            if (StringUtils.hasText(userFaceImage)) {
                if (!userFaceImage.equals(userFace.getUserFaceImage())) {
                    String feature = faceService.face2Feature(userFaceImage);
                    userFace.setUserFaceImage(userFaceImage);
                    userFace.setUserFaceFeature(feature);
                    this.updateById(userFace);
                }
            } else {
                userFace.setUserFaceImage("");
                userFace.setUserFaceFeature("");
                this.updateById(userFace);
            }
        }
    }
}
